const fs = require("fs/promises")
const path = require("path")
const connection = require('./database')
const getProvinceListSql = 'SELECT bc.id, bc.code value,bc.name label from base_cnarea bc WHERE ISNULL(pid);'
const getCityOrAreaListSql = 'SELECT bc.id, bc.code value,bc.name label from base_cnarea bc WHERE pid = ?;'
async function start() {
  // 查询所有省级单位
  const [provinceList] = await connection.query(getProvinceListSql)

  for (let Pi = 0; Pi < provinceList.length; Pi++) {
    const provinceItem = provinceList[Pi]
    const provinceID = provinceItem.id
    // 查该省下所有市
    const [cityList] = await connection.query(getCityOrAreaListSql, provinceID)
    provinceItem.children = cityList

    // 如果不需要区的信息 可注释掉此处
    // ------------------------------------
    for (let Ci = 0; Ci < cityList.length; Ci++) {
      const cityItem = cityList[Ci];
      const cityID = cityItem.id
      const [areaList] = await connection.query(getCityOrAreaListSql, cityID)
      cityItem.children = areaList
    }
    // ------------------------------------
    console.log(provinceItem.label + '-----已完成')
    if ((Pi + 1) === provinceList.length) {
      console.log('已全部完成')
    }
  }
  await fs.writeFile(path.resolve(__dirname, './cn-area.json'), JSON.stringify(provinceList))
}

start()
